package cc.risingsun.wing.core.generator;

import java.lang.annotation.Annotation;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.risingsun.wing.annotations.WingMethod;
import cc.risingsun.wing.annotations.WingType;
import cc.risingsun.wing.ds.DataStruct;

/**
 * 
 * @author iron.yin@gmail.com
 * @sina 2012-8-30
 */
public final class WingGeneratorUtil {

	private static Logger logger = LoggerFactory.getLogger(WingGeneratorUtil.class);

	private static Map<Class<? extends Annotation>, WingTypeGenerator> typeHandlers = DataStruct.hashMap();

	private static Map<Class<? extends Annotation>, WingMethodGenerator> methodHandlers = DataStruct.hashMap();

	public static void registerTypeAnnotations(Class<? extends Annotation>... annotations) {
		Class<? extends WingTypeGenerator> clazz;
		WingTypeGenerator handler = null;
		for (Class<? extends Annotation> cla : annotations) {
			if (!typeHandlers.containsKey(cla)) {
				WingType anno = cla.getAnnotation(WingType.class);
				if (anno != null) {
					clazz = anno.value();
					try {
						handler = clazz.newInstance();
					} catch (Exception e) {
						logger.error("registerTypeAnnotations occur a error," + e.getMessage(), e);
						continue;
					}
					typeHandlers.put(cla, handler);
					continue;
				}
				logger.warn(cla.getName() + " without config WingType");
			}
		}
	}

	public static void registerMethodAnnotations(Class<? extends Annotation>... annotations) {
		Class<? extends WingMethodGenerator> clazz;
		WingMethodGenerator handler = null;
		for (Class<? extends Annotation> cla : annotations) {
			if (!methodHandlers.containsKey(cla)) {
				WingMethod anno = cla.getAnnotation(WingMethod.class);
				if (anno != null) {
					clazz = anno.value();
					try {
						handler = clazz.newInstance();
					} catch (Exception e) {
						logger.error("registerMethodAnnotations occur a error," + e.getMessage(), e);
						continue;
					}
					methodHandlers.put(cla, handler);
					continue;
				}
				logger.warn(cla.getName() + " without config WingMethod");
			}
		}
	}

	public static WingTypeGenerator getTypeGenerator(Class<? extends Annotation> annotation) {
		return typeHandlers.get(annotation);
	}

	public static WingMethodGenerator getMethodGenerator(Class<? extends Annotation> annotation) {
		return methodHandlers.get(annotation);
	}

}
